package com.disruptor.base;

import java.nio.ByteBuffer;

import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.RingBuffer;

/**
 * 事件生产者,改进版
 * Disruptor 3.0提供了lambda式的API。这样可以把一些复杂的操作放在Ring Buffer，
 * 所以在Disruptor3.0以后的版本最好使用Event Publisher或者Event Translator来发布事件
 */
public class LongEventProducerWithTranslator {
    /**
     * EventTranslatorOneArg是一个泛型类，比如EventTranslatorOneArg<TargetEventModel,SourceEventModel>，
     * 被用在disruptor发布事件event的时候作为参数传入。
     * disruptor发布event后，会执行这个类的translateTo方法，
     * 作用是：将SourceEventModel转换成TargetEventModel，
     * 然后disruptor中的handler链就消费TargetEventModel对象
     */
    private static final EventTranslatorOneArg<LongEvent, ByteBuffer> TRANSLATOR =
            new EventTranslatorOneArg<LongEvent, ByteBuffer>() {
                @Override
                public void translateTo(LongEvent event, long sequeue, ByteBuffer buffer) {
                    event.setValue(buffer.getLong(0));
                }
            };
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducerWithTranslator(RingBuffer<LongEvent> ringBuffer) {
        this.ringBuffer = ringBuffer;
    }

    public void onData(ByteBuffer buf) {
        //ringBuffer.publishEvent(TRANSLATOR, buffer);
        //lambda写法:将传递的参数数据转换设置给event,消费者就直接消费event
        ringBuffer.publishEvent((event, sequeue, buffer) -> {
            event.setValue(buffer.getLong(0));
        }, buf);
    }
}
